import { _decorator, Component, Node, screen, view, ResolutionPolicy,game } from "cc"
const { ccclass, property,disallowMultiple,menu } = _decorator

@ccclass("AdaptScreenManager")
@disallowMultiple(true)
@menu("adaptScreen/AdaptScreenManager")
export class AdaptScreenManager extends Component {
  private _designWidth: number
  private _designHeight: number

  get designWidth() {
    return this._designWidth
  }
  get designHeight() {
    return this._designHeight
  }
  get isPortrait() {
    return this.designHeight > this.designWidth
  }
  get isLandscape() {
    return this.designWidth > this.designHeight
  }
  onLoad() {
    const size = view.getDesignResolutionSize()
    this._designWidth = size.width
    this._designHeight = size.height
    view.on("canvas-resize", this.onCanvasResize, this)
    this.onCanvasResize()
  }

  onCanvasResize() {
    const windowSize = screen.windowSize
    this.resetDesignResolutionSize(windowSize.width, windowSize.height)
    game.emit("window-resize")
  }

  resetDesignResolutionSize(width: number, height: number) {
    if (
      (width > height && this._designWidth < this._designHeight) ||
      (width < height && this._designWidth > this._designHeight)
    ) {
      this.swapDesignSize()
    }
    const i = (this._designWidth / width + this._designHeight / height) / 2
    const n = width * i
    const s = height * i
    view.setDesignResolutionSize(n, s, ResolutionPolicy.SHOW_ALL)
  }

  swapDesignSize() {
    const e = this.designWidth
    ;(this._designWidth = this.designHeight), (this._designHeight = e)
  }
}
